#include <QtCore>

#include "RoQuery.h"

#include "TestComponent.h"


int main(int argc, char * argv[])
{
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));

    QCoreApplication app(argc, argv);

    QString runtimeDebugEnv = qgetenv("DEBUG").toLower();
    bool runtimeDebug = false;
    if ( not runtimeDebugEnv.isEmpty() )
    {
        if ( runtimeDebugEnv == "0" or
             runtimeDebugEnv == "false" or
             runtimeDebugEnv == "no" or
             runtimeDebugEnv == "off" )
        {
            runtimeDebug = false;
        }
        else
        {
            runtimeDebug = true;
        }
    }

    QPointer<RoModule> module = new RoModule(&app, runtimeDebug);
    QPointer<TestComponent> component = new TestComponent(module);

    QObject::connect(module, SIGNAL( error(QAbstractSocket::SocketError) ),
                     &app, SLOT( quit() ));
    QObject::connect(module, SIGNAL( connected() ),
                     component, SLOT( runTest() ));
    QObject::connect(component, SIGNAL( testFinished() ),
                     &app, SLOT( quit() ));

    module->connectToNetwork("localhost");

    app.exec();

    return component->result ? 0 : __LINE__;
}


TestComponent::TestComponent(RoModule * module):
    super(module),
    result(false)
{
    setName("test");
}


void TestComponent::runTest()
{
    result = false; // be pessimistic

    Q_ASSERT( qApp->arguments().size() >= 3 );
    QString component = qApp->arguments()[1],
            method = qApp->arguments()[2];

    QPointer<RoQuery> query;
    Q_ASSERT( query = createSimpleQuery(component, method) );

    if ( qApp->arguments().size() >= 4 )
    {
        QDomDocument argument;
        argument.setContent(QString( qApp->arguments()[3] ));
        Q_ASSERT( query->exec(argument) );
    }
    else
    {
        Q_ASSERT( query->exec() );
    }
}


void TestComponent::receive_query_datum(QDomDocument datum)
{
    //RoQuery * query = qobject_cast<RoQuery*>(sender());
    qDebug() << datum.documentElement().tagName() << ':' << datum.documentElement().text();
}


void TestComponent::receive_query_result(bool error, QDomDocument answer)
{
    RoQuery * query = qobject_cast<RoQuery*>(sender());
    if ( error )
    {
        qDebug() << "Error happened with query" << query->rid().toString() << ':'
                 << answer.documentElement().tagName() << ':'
                 << answer.documentElement().firstChildElement("description").text();
    }
    else
    {
        result = true;
        qDebug() << "Got result from query" << query->rid().toString() << static_cast<const char *>((":\n" + answer.toString(4)).toUtf8());
    }

    sender()->deleteLater();

    emit testFinished();
}
